//
//  YJEmotionView.m
//  YJB
//
//  Created by 韦朝宾 on 16/5/22.
//  Copyright © 2016年 YJB. All rights reserved.
//

#import "YJMoreItemView.h"
#import "YJMoreItemButton.h"
#import "Masonry.h"
#import <AVFoundation/AVFoundation.h>
//#import "VoiceConverter.h"
#import "YJNetworkTool.h"
#import "YJRecordTipsView.h"
//#import "ECDevice.h"
//#import "DeviceDelegateHelper.h"

#define PADDING ((IPHONE_W - 240) / 4)
@interface YJMoreItemView()<UIScrollViewDelegate>
@property(nonatomic,weak)UIScrollView *scrollView;
@property(nonatomic,weak)UIPageControl *page;
@property(nonatomic,strong)NSString  *recorderWavPath;
@property(nonatomic,strong)AVAudioRecorder  *recorder;

@property(nonatomic,weak)YJRecordTipsView *recordTipsView;

@property(nonatomic,strong)NSTimer  *timer;

@property(nonatomic,strong)UIView *maskView;

@property(nonatomic,weak)UIView *voiceBgView;
//是否已获取麦克风权限
@property(nonatomic,assign)BOOL isAllowRecord;

@end

@implementation YJMoreItemView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor = WHITECOLOR;
        [self createButtons];
        [self createBottomView];
        [self page];
    }
    return self;
}

-(UIScrollView *)scrollView
{
    if (_scrollView == nil)
    {
        UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_W, 135)];
        scrollView.showsVerticalScrollIndicator = NO;
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.contentSize = CGSizeMake(2 * IPHONE_W, scrollView.height);
        scrollView.pagingEnabled = YES;
        scrollView.delegate = self;
        [self addSubview:scrollView];
        _scrollView = scrollView;
    }
    return _scrollView;
}

-(UIPageControl *)page
{
    if (_page == nil)
    {
        UIPageControl *page = [[UIPageControl alloc]init];
        page.userInteractionEnabled = NO;
        [self addSubview:page];
        _page = page;
        page.numberOfPages = 2;
        page.pageIndicatorTintColor = MYCOLOR(213, 213, 213);
        page.currentPageIndicatorTintColor = MYCOLOR(176, 176, 176);
        [page mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.top.mas_equalTo(self.scrollView.mas_bottom);
            make.height.mas_equalTo(5);
        }];
    }
    return _page;
}

- (void)createButtons
{
    UIView *firstView = [[UIView alloc]init];
    firstView.x = 0;
    firstView.y = 0;
    firstView.width = IPHONE_W;
    firstView.height = self.scrollView.height;
    [self.scrollView addSubview:firstView];
    
    UIView *secondView = [[UIView alloc]init];
    secondView.x = IPHONE_W;
    secondView.y = 0;
    secondView.width = IPHONE_W;
    secondView.height = self.scrollView.height;
    [self.scrollView addSubview:secondView];
    
    NSMutableArray *firstButtons = [NSMutableArray array];
    NSMutableArray *secondButtons = [NSMutableArray array];
//    NSArray *titles = @[@"图片",@"拍摄",@"红包",@"转账",@"小视频",@"视频聊天",@"定位",@"语音输入"];
        NSArray *titles = @[@"图片",@"拍摄",@"红包",@"转账",@"定位",@"",@"",@""];
//    NSArray *images =  @[@"photo_icon",@"shooting_icon",@"red_icon",@"transfer_icon",@"video",@"video-chat_icon",@"pos_icon",@"voice-input_icon"];
    NSArray *images = @[@"photo_icon",@"shooting_icon",@"red_icon",@"transfer_icon",@"pos_icon",@"",@"",@""];
    for (int i = 0; i < titles.count; i ++)
    {
        YJMoreItemButton *button = [[YJMoreItemButton alloc]init];
        button.tag = i + 1;
        [button setTitle:titles[i] forState:UIControlStateNormal];
        [button setTitleColor:kUIColorFromRGB(0x666666)  forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15.0f];
        [button setImage:Image(images[i]) forState:UIControlStateNormal];
        [button addTarget:self action:@selector(moreItemButtonCLick:) forControlEvents:UIControlEventTouchUpInside];
        if (i < 4)
        {
            [firstButtons addObject:button];
            [firstView addSubview:button];
        }
        else
        {
            [secondButtons addObject:button];
            [secondView addSubview:button];
        }
    }
    //第一部分添加约束
    [firstButtons mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:65 leadSpacing:PADDING * 0.5 tailSpacing:PADDING * 0.5];
    [firstButtons mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@20);
        make.bottom.mas_equalTo(0);
    }];
    //第二部分添加约束
    [secondButtons mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:65 leadSpacing:PADDING * 0.5 tailSpacing:PADDING * 0.5];
    [secondButtons mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@20);
        make.bottom.mas_equalTo(0);
    }];

}
- (void)createBottomView
{
    UIButton *videoBtn = [[UIButton alloc]init];
    [videoBtn setImage:Image(@"video_icon") forState:UIControlStateNormal];
    [self addSubview:videoBtn];
    [videoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.bottom.mas_equalTo(-5);
        make.width.height.mas_equalTo(60);
    }];
    
    UIButton *voiceBtn = [[UIButton alloc]init];
    [voiceBtn setImage:Image(@"voice_icon") forState:UIControlStateNormal];
    [self addSubview:voiceBtn];
    [voiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-5);
        make.width.height.mas_equalTo(60);
    }];
    
    UIButton *inputBtn = [[UIButton alloc]init];
    [inputBtn setBackgroundImage:Image(@"hold-the-box_hl") forState:UIControlStateNormal];
    [inputBtn setBackgroundImage:Image(@"hold-the-box_click") forState:UIControlStateHighlighted];
    [inputBtn setTitle:@"按住说话" forState:UIControlStateNormal];
    [inputBtn setTitleColor:kUIColorFromRGB(0x999999) forState:UIControlStateNormal];
    [inputBtn addTarget:self action:@selector(inputBtnTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    [inputBtn addTarget:self action:@selector(inputBtnTouchDown:) forControlEvents:UIControlEventTouchDown];
    [inputBtn addTarget:self action:@selector(inputBtnTouchOutside:) forControlEvents:UIControlEventTouchUpOutside];
    //手指从按钮内部拖到外部时触发
    [inputBtn addTarget:self action:@selector(inputBtnTouchDragOutside:) forControlEvents:UIControlEventTouchDragOutside];
    //手指从按钮外部拖到内部时触发
    [inputBtn addTarget:self action:@selector(inputBtnTouchDragInside:) forControlEvents:UIControlEventTouchDragInside];
    
    
    [self addSubview:inputBtn];
    [inputBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-15);
        make.left.mas_equalTo(videoBtn.mas_right);
        make.right.mas_equalTo(voiceBtn.mas_left);
        make.height.mas_equalTo(40);
    }];
}

#pragma mark------------------------ 事件监听
- (void)inputBtnTouchDown:(UIButton *)inputBtn
{
    
    AVAuthorizationStatus audioAuthStatus =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (audioAuthStatus == AVAuthorizationStatusRestricted || audioAuthStatus == AVAuthorizationStatusDenied)
    {
        self.isAllowRecord = NO;
        UIAlertController *alterC = [UIAlertController alertTitle:@"无法录音" message:@"请在iPhone的“设置-隐私-麦克风”选项中，允许赢金宝访问你的手机麦克风"];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alterC animated:YES completion:nil];
    }else//有权限
    {
      self.isAllowRecord = YES;
      [self startRecord];
    }
}

- (void)inputBtnTouchUpInside:(UIButton *)inputBtn
{
    if (_isAllowRecord)
    {
        [self completeRecord];
    }
}

- (void)inputBtnTouchOutside:(UIButton *)inputBtn
{
    if (_isAllowRecord)
    {
      [self cancelRecord];  
    }
}

- (void)inputBtnTouchDragOutside:(UIButton *)inputBtn
{
    self.recordTipsView.isCancel = YES;
}

- (void)inputBtnTouchDragInside:(UIButton *)inputBtn
{
    self.recordTipsView.isCancel = NO;
}

- (void)startRecord
{
    UIWindow *keywindow = [UIApplication sharedApplication].keyWindow;
    UIView *voiceBgView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    YJRecordTipsView *recordTipsView = [YJRecordTipsView getRecordTipsView];
    recordTipsView.isCancel = NO;
    recordTipsView.layer.cornerRadius = 7;
    _recordTipsView = recordTipsView;
    recordTipsView.width = recordTipsView.height = 137;
    recordTipsView.centerX = voiceBgView.centerX;
    recordTipsView.centerY = voiceBgView.centerY - 30;
    [voiceBgView addSubview:recordTipsView];
    [keywindow addSubview:voiceBgView];
    self.voiceBgView = voiceBgView;
    UIView *maskView = [[UIView alloc]init];
    maskView.backgroundColor = WHITECOLOR;
    self.maskView = maskView;
    
    //文件名
    NSString *timeStr = [NSString stringWithCurrentTimeString];
    //添加后缀名
    NSString *fileName = [timeStr stringByAppendingPathExtension:@"wav"];
    //wav音频路径
    self.recorderWavPath = cachesFilePath(fileName);
    //录音URL
    NSURL *recorderUrl = [NSURL URLWithString:self.recorderWavPath];
//    AVAudioRecorder *recorder = [[AVAudioRecorder alloc]initWithURL:recorderUrl settings:[VoiceConverter GetAudioRecorderSettingDict] error:nil];
    //配置录音
//    AVAudioSession *avSession = [AVAudioSession sharedInstance];
//    [avSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
//    [avSession setActive:YES error:nil];
//    recorder.meteringEnabled = YES;
//    [recorder prepareToRecord];
//    [recorder record];
//    self.recorder = recorder;
//    //开始计时
//    _timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];
}

-(void)completeRecord
{
    [_timer invalidate];
    _timer = nil;
    [self.recordTipsView removeFromSuperview];
    [self.voiceBgView removeFromSuperview];
    [self.recorder stop];
    AVAudioPlayer *voicePlay = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:self.recorderWavPath] error:nil];
    if (voicePlay.duration < 0.5)
    {
        [MBProgressHUD showError:@"录音时间过短"];
        return;
    }
//    //amr保存路径
//    NSString *amrPath = [[self.recorderWavPath stringByDeletingPathExtension] stringByAppendingPathExtension:@"amr"];
//    //转码，成功后删除原来的文件
//    NSFileManager *voiceManager = [NSFileManager defaultManager];
//    if ([VoiceConverter ConvertWavToAmr:self.recorderWavPath amrSavePath:amrPath])
//    {
//        [voiceManager removeItemAtPath:self.recorderWavPath error:nil];
//    }
//    NSString *voiceTimeString = [NSString stringWithFormat:@"%d",(int)(voicePlay.duration + 0.5)];
//    if (_voiceRecoedBlock)
//        _voiceRecoedBlock(amrPath.lastPathComponent,voiceTimeString);
}

-(void)cancelRecord
{
    [_timer invalidate];
    _timer = nil;
    [self.recordTipsView removeFromSuperview];
    [self.voiceBgView removeFromSuperview];
    [self.recorder stop];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:self.recorderWavPath])
    {
        [fileManager removeItemAtPath:self.recorderWavPath error:nil];
    }
}

- (void)changeImage
{
    [self.recorder updateMeters];//更新测量值
    //取平均值
    float avg = [self.recorder averagePowerForChannel:0];
    //设置最小分贝
    float minValue = -60;
    //60作为获取分配的范围
    float range = 60.0;
    //把100作为输出分贝范围
    float outRange = 100.0;
    if (avg < minValue)
        avg = minValue;
    
    float decibels = (avg + range) / range * outRange;
    _maskView.layer.frame = CGRectMake(0, _recordTipsView.yinjieView.height - decibels * _recordTipsView.yinjieView.height / 100, _recordTipsView.yinjieView.width,_recordTipsView.yinjieView.height);
    _recordTipsView.yinjieView.layer.mask = _maskView.layer;
}

- (void)moreItemButtonCLick:(YJMoreItemButton *)button
{
    YJMoreItemViewButtonType type = 0;
    switch (button.tag)
    {
        case 1:
            type = YJMoreItemViewButtonTypeAlbum;
            break;
        case 2:
         type = YJMoreItemViewButtonTypeCamera;
            break;
        case 3:
            type = YJMoreItemViewButtonTypeWallet;
            break;
        case 4:
            type = YJMoreItemViewButtonTypeTransferAccount;
                    break;
        case 5:
         type = YJMoreItemViewButtonTypeVideo;
            break;
        case 6:
         type = YJMoreItemViewButtonTypeVideoChat;
            break;
        case 7:
         type = YJMoreItemViewButtonTypeLocation;
            break;
        case 8:
         type = YJMoreItemViewButtonTypeVoiceRecord;
            break;
    }
    
    if (self.moreItemBlock)
        self.moreItemBlock(type);
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger currentPage = (int)(scrollView.contentOffset.x / IPHONE_W + 0.5);
    self.page.currentPage = currentPage;
}


@end
